#pragma once
#include"Headerfile.hpp"
namespace shw
{
#define BUFFER_DEFAULT_SIZE (1 * 1024 * 1024)
#define BUFFER_INCREMENT_SIZE (5 * 1024 * 1024)  // 线性增长
#define BUFFER_THRESHOLD_SIZE (50 * 1024 * 1024) // 阈值

    class Buffer
    {
    public:
        Buffer()
            : _writePointer(0), _readPointer(0) { _v.resize(BUFFER_DEFAULT_SIZE); }
        void Reset() // 读写指针清0
        {
            _writePointer = 0;
            _readPointer = 0;
        }
        size_t ReadAbleSize() // 可读数据量
        {
            return _writePointer - _readPointer;
        }
        size_t WriteAbleSize() // 可写数据量
        {
            return _v.size() - _writePointer;
        }
        bool Empty() // 判断缓冲区是否为空
        {
            return _writePointer == _readPointer;
        }
        void Push(const char *data, size_t len) // 放数据
        {
            EnoughSize(len);
            std::copy(data, data + len, &_v[_writePointer]);
            _writePointer += len;
        }
        void Pop(size_t len) // 拿数据，更新指针
        {
            _readPointer += len;
            assert(_readPointer <= _writePointer);
        }
        void Swap(Buffer &buf)
        {
            _v.swap(buf._v);
            std::swap(_writePointer, buf._writePointer);
            std::swap(_readPointer, buf._readPointer);
        }
        const char *Begin()
        {
            return &_v[_readPointer];
        }
        size_t GetWriteP() { return _writePointer; }
        size_t GetReadP() { return _readPointer; }
        std::vector<char> Getvector() { return _v; }

    protected:
        void EnoughSize(const size_t len)
        {
            if (WriteAbleSize() >= len)
                return; // 可写数据量大于这次写入数据量
            size_t newCap;
            if (_v.size() < BUFFER_THRESHOLD_SIZE)
            {
                newCap = _v.size() * 2 + len; // 加len为了防止2倍扩容后仍然小于len,加len一定大于len
                _v.resize(newCap);
            }
            else
            {
                newCap = _v.size() + BUFFER_INCREMENT_SIZE + len; // 超过阈值就线性增长
            }
        }

    private:
        size_t _writePointer; // 写指针
        size_t _readPointer;  // 读指针
        std::vector<char> _v; // 用vector管理数据
    };
}